package tingshu.servlet.Home;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import tingshu.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 首页的专辑展示(专辑id，用户名，专辑名，专辑封面)
 * @author houdaiqin
 * @date 2022/07/20 19:35
 **/
@WebServlet("/album-list.json")
public class AlbumListServlet extends HttpServlet {

    public static class AlbumView{
        public Integer aid;
        public String username;
        public String title;
        public String cover;

        public AlbumView(Integer aid, String username,String title, String cover) {
            this.aid = aid;
            this.username=username;
            this.title = title;
            this.cover = cover;
        }
    }
    public static class ResultView{
        public List<AlbumView> albumList=new ArrayList<>();
    }

    @Override
    @SneakyThrows
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ResultView resultView=new ResultView();
        try(Connection c= DBUtil.connection()){
            //联表查询
            String sql="select aid,username,title,cover from albums a join users u on a.uid = u.uid where state=2 order by aid";
            try(PreparedStatement ps=c.prepareStatement(sql)){
                try(ResultSet rs=ps.executeQuery()){
                    while (rs.next()){
                        AlbumView view=new AlbumView(
                                rs.getInt("aid"),
                                rs.getString("username"),
                                rs.getString("title"),
                                rs.getString("cover")
                        );
                        resultView.albumList.add(view);
                    }
                }
            }
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(resultView);

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().println(json);
    }
}